<!-- 公共文件 start -->
@extends('admin.public.base')
@section('style')
<style>
    .layui-form-switch {
        background-color: #1E9FFF !important;
    }
    .layui-form-switch.layui-form-onswitch {
        background-color: #5FB878 !important;
    }
</style>
@endsection
<!-- 公共文件 end -->

@php
    $express_id = $express_id ?? ($data['express_id'] ?? 0);
@endphp

@section('content')
    <div class="layui-fluid">
        <div class="layui-row">
            <input type="hidden" name="order_sn" value="{{$data['order_sn']}}">
            <form class="layui-form">
                <div class="layui-form-item" style="text-align:center;font-size:18px;">
                    <b>出货订单号：{{$data['order_sn']}}</b>

                    <a href="/admin/order/orderPdf?id={{$data['id']}}">
                        <div class="icon iconfont" style="float:right;">&#xe6c9;</div>
                    </a>
                </div>
                <hr>
                <div class="layui-form-item">
                    <label class="layui-form-label"><b>代理商信息：</b></label>
                    <div class="layui-input-block" style="line-height:36px">
                        {{$storeInfo['store_name']}}<br>
                        货款余额：{{$storeInfo['money_goods']}}元<br>
                        管理费余额：{{$storeInfo['money_management']}}元 <br>
                        联系人：{{$storeInfo['principal_name']}}，手机号：{{$storeInfo['principal_mobile']}}
                        ，地址：{{$storeInfo['principal_address']}}
                    </div>
                </div>
                <hr>
                <div class="layui-form-item layui-table-body layui-table-main" style="display: flex;">
                    <div class="layui-col-xs6" style="height:400px; float:left;padding:15px">
                        <b>待选商品</b><br>
                        <table class="layui-table" lay-skin="line" style="table-layout:fixed">
                            <colgroup>
                                <col width="10">
                                <col width="10">
                                <col width="10">
                                <col width="45">
                                <col width="10">
                                <col width="15">
                            </colgroup>
                            <thead>
                            <tr>
                                <th>
                                    <input type="checkbox" lay-filter="checkall-left" name="" lay-skin="primary">
                                </th>
                                <th>分类</th>
                                <th>编号</th>
                                <th>商品名</th>
                                <th>单件价格</th>
                                <th>商品库存</th>
                            </tr>
                            </thead>
                            <tbody class="goodsList1">
                            @foreach( $repertoryList as $kk => $item)
                                <tr data-item-id="{{$item['id']}}">
                                    <td onClick="removeDiv(this,{{$kk}},1)"><i class="iconfont" style="color:#1ABC9C">&#xe6b9;</i></td>
                                    <td>{{ $item['cate_name'] }}</td>
                                    <td>{{ $item['goods_sn'] }}</td>
                                    <td>{{ $item['goods_name'] }}</td>
                                    <td>{{ $item['goods_price'] }}</td>
                                    <td>{{ $item['goods_sale_num'] }}</td>
                                </tr>
                            @endforeach

<script>
let selectedGoodsNames = new Set();

$(document).ready(function() {
    // 初始化已选商品名称集合
    $('.goodsList2 tr').each(function() {
        let goodsName = $(this).find('td:eq(2)').text().trim(); // 第3列是商品名
        if (goodsName) {
            selectedGoodsNames.add(goodsName);
        }
    });
    updateAvailableGoodsVisibility();
});

function updateAvailableGoodsVisibility() {
    $('.goodsList1 tr').each(function() {
        let $tr = $(this);
        let goodsName = $tr.find('td:eq(3)').text().trim(); // 第4列是商品名
        
        if (goodsName) {
            if (selectedGoodsNames.has(goodsName)) {
                $tr.fadeOut(300);
            } else {
                $tr.fadeIn(300);
            }
        }
    });
}

function removeDiv(obj, i, type) {
    if (type == 1) {
        // 添加到已选商品
        var goodsName = reDataArr[i].goods_name;
        var $existingRow = $('.goodsList2 tr').filter(function() {
            return $(this).find('td:eq(2)').text().trim() === goodsName;
        });

        if ($existingRow.length) {
            // 已存在相同商品名的行，累加数量
            var $input = $existingRow.find('.goods-number');
            var currentValue = parseInt($input.val()) || 0;
            $input.val(currentValue + 1).trigger('change');
                    
                    // 更新隐藏域中的商品ID（可能需要合并多个ID的情况）
                    var goodsIdInput = $existingRow.find('input[name$="[goods_id]"]');
                    var existingId = goodsIdInput.val();
                    if (existingId !== reDataArr[i].id.toString()) {
                        // 如果商品ID不同但名称相同，可能需要特殊处理（如保留多个ID记录）
                        goodsIdInput.val(existingId + ',' + reDataArr[i].id);
                    }
                } else {
                    // 不存在则创建新行
                    var batchOptions = '';
                    if (reDataArr[i].batch_list && reDataArr[i].batch_list.length > 0) {
                        batchOptions += '<option value="">请选择批次</option>';
                        for (var b = 0; b < reDataArr[i].batch_list.length; b++) {
                            batchOptions += '<option value="' + reDataArr[i].batch_list[b] + '">' + reDataArr[i].batch_list[b] + '</option>';
                        }
                    } else {
                        batchOptions = '<option value="">无可选批次</option>';
                    }

                    var htmlStr = `<tr data-item-id="${reDataArr[i].id}">` +
                            `<td onClick="removeDiv(this,${i},2)"><i class="iconfont" style="color:#DE1C31">&#xe6fe;</i></td>` +
                            `<td>${reDataArr[i].cate_name}</td>` +
                            `<td>${reDataArr[i].goods_name}</td>` +
                            `<td>${reDataArr[i].goods_price}</td>` +
                            `<td>
                                <input type="number" name="goods[${reDataArr[i].id}][goods_number]" value="1" min="1" step="1" class="layui-input goods-number">
                                <input type="hidden" name="goods[${reDataArr[i].id}][goods_id]" value="${reDataArr[i].id}">
                                <input type="hidden" name="goods[${reDataArr[i].id}][goods_price]" value="${reDataArr[i].goods_price}">
                                <input type="hidden" name="goods[${reDataArr[i].id}][is_give]" value="0">
                                <input type="hidden" name="goods[${reDataArr[i].id}][goods_pid]" value="${reDataArr[i].goods_pid || ''}">
                                <input type="hidden" name="goods[${reDataArr[i].id}][type]" value="${reDataArr[i].type || ''}">
                                <input type="hidden" name="goods[${reDataArr[i].id}][goods_weight_m]" value="${reDataArr[i].goods_weight_m || 0}">
                            </td>` +
                            `<td>否</td>` +
                            `<td>
                                <select name="goods[${reDataArr[i].id}][batch]" class="layui-input batch-select" lay-verify="required" lay-reqtext="请选择入库批次">
                                    ${batchOptions}
                                </select>
                            </td>` +
                        `</tr>`;

                    $(".goodsList2").prepend(htmlStr);
                    layui.form.render('select');

                    var $newSelect = $('.goodsList2 tr[data-item-id="' + reDataArr[i].id + '"]').find('.batch-select');
                    if ($newSelect.find('option').length > 1) {
                        $newSelect.val($newSelect.find('option:eq(1)').val());
                    } else if ($newSelect.find('option').length === 1 && $newSelect.find('option').val() === '') {
                        $newSelect.removeAttr('lay-verify');
                        $newSelect.removeAttr('lay-reqtext');
                    }
                    layui.form.render('select');
                    
                    // 添加新商品到集合
                    selectedGoodsNames.add(goodsName);
                }
                updateAvailableGoodsVisibility();
            } else if (type == 2) {
                // 移除商品逻辑保持不变
                var $tr = $(obj).parent();
                var goodsName = $tr.find('td:eq(2)').text().trim();
                
                $tr.remove();
                if (goodsName) {
                    selectedGoodsNames.delete(goodsName);
                    updateAvailableGoodsVisibility();
                }
            } else if (type == 3) {
                // 删除已选商品逻辑保持不变
                let $tr = $(obj).parent();
                let goodsName = $tr.find('td:eq(2)').text().trim();
                
                $tr.remove();
                if (goodsName) {
                    selectedGoodsNames.delete(goodsName);
                    updateAvailableGoodsVisibility();
                }
            }
            
            // 更新总数量和运费
            updateTotalNumber();
            updateFreightAndAmount();
        }
</script>
                            </tbody>
                        </table>
                    </div>
                    <div class="layui-col-xs6" style="float:right; height:400px; padding:15px">
                        <b>已选商品</b><br>
                        <table class="layui-table" lay-skin="line" style="table-layout:fixed">
                            <colgroup>
                                <col width="10">
                                <col width="10">
                                <col width="40">
                                <col width="10">
                                <col width="20">
                                <col width="15">
                                <col width="20">
                            </colgroup>
                            <thead>
                            <tr>
                                <th>
                                    <input type="checkbox" lay-filter="checkall-left" name="" lay-skin="primary">
                                </th>
                                <th>分类</th>
                                <th>商品名</th>
                                <th>单件价格</th>
                                <th>商品数量</th>
                                <th>是否赠送</th>
                                <th>入库批次</th>
                            </tr>
                            </thead>
                            <tbody class="goodsList2">
                            @foreach( $goodsList as $kk => $item)
                                <tr data-item-id="{{$item['id']}}" data-type="{{$item['type']}}" data-pid="{{$item['goods_pid']}}" data-group-number="{{$item['goods_group_number']}}">
                                    <td onClick="removeDiv(this,{{$kk}},3)"><i class="iconfont" style="color:#1ABC9C">&#xe6fe;</i>
                                    </td>
                                    <td>{{ $item['cate_name'] }}</td>
                                    <td>{{ $item['goods_name'] }}</td>
                                    <td>{{ $item['goods_price'] }}</td>
                                    <td>
                                        @if($item['type'] == 2)
                                            <!-- 组合商品，数量不可编辑 -->
                                            <input type="number" name="goods[{{$item['id']}}][goods_number]" 
                                                   value="{{ $item['goods_number'] }}" min="1" step="1" class="layui-input goods-number" readonly>
                                        @else
                                            <!-- 普通商品，数量可编辑 -->
                                            <input type="number" name="goods[{{$item['id']}}][goods_number]"
                                                   value="{{ $item['goods_number'] }}" min="1" step="1" class="layui-input goods-number">
                                        @endif
                                        <input type="hidden" name="goods[{{$item['id']}}][goods_id]"
                                               value="{{ $item['goods_id'] }}">
                                        <input type="hidden" name="goods[{{$item['id']}}][goods_price]"
                                               value="{{ $item['goods_price'] }}">
                                        <input type="hidden" name="goods[{{$item['id']}}][is_give]"
                                               value="{{ $item['is_give'] }}">
                                        <input type="hidden" name="goods[{{$item['id']}}][goods_pid]"
                                               value="{{ $item['goods_pid'] }}">
                                        <input type="hidden" name="goods[{{$item['id']}}][type]"
                                               value="{{ $item['type'] }}">
                                        <input type="hidden" name="goods[{{$item['id']}}][goods_weight_m]"
                                               value="{{ $item['goods_weight_m'] ?? 0 }}">
                                        @if($item['type'] == 2 && $item['goods_pid'] == 0)
                                            <!-- 组合商品主商品，存储子商品信息 -->
                                            <input type="hidden" class="group-main-number" value="{{ $item['goods_number'] }}">
                                        @endif
                                    </td>
                                    <td>@if($item['is_give'] == 1) <b style="color:#F03752">是</b> @else <b>否</b> @endif
                                    </td>
                                    <td>
                                        @if(!empty($item['store_product_batch']))
                                            <select name="goods[{{$item['id']}}][batch]" class="layui-input batch-select" lay-verify="required" lay-reqtext="请选择入库批次">
                                                <option value="{{ $item['store_product_batch'] }}">{{ $item['store_product_batch'] }}</option>
                                                @foreach($goodsBatchInfo[$item['goods_id']] ?? [] as $batch)
                                                    @if($batch != $item['store_product_batch'])
                                                        <option value="{{ $batch }}">{{ $batch }}</option>
                                                    @endif
                                                @endforeach
                                            </select>
                                        @else
                                            <select name="goods[{{$item['id']}}][batch]" class="layui-input batch-select" lay-verify="required" lay-reqtext="请选择入库批次">
                                                <option value="">请选择批次</option>
                                                @foreach($goodsBatchInfo[$item['goods_id']] ?? [] as $batch)
                                                    <option value="{{ $batch }}">{{ $batch }}</option>
                                                @endforeach
                                            </select>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
                <hr>
                <div class="layui-form-item">
                    <label class="layui-form-label"><b>收货信息：</b></label>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label"><span class="x-red">*</span>收货人</label>
                        <div class="layui-input-inline">
                            <input type="text" name="order_name" lay-verify="required" lay-reqtext="必填项,请填写信息"
                                   value="{{ $data['order_name'] }}" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label"><span class="x-red">*</span>收货人电话</label>
                        <div class="layui-input-inline">
                            <input type="text" name="order_mobile" lay-verify="required" lay-reqtext="必填项,请填写信息"
                                   value="{{ $data['order_mobile'] }}" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>省市区</label>
                    <div class="layui-input-inline">
                        <input type="text" name="order_province" lay-verify="required" lay-reqtext="必填项,请填写信息"
                               value="{{ $data['order_province'] }}" class="layui-input" id="order_province">
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" name="order_city" lay-verify="required" lay-reqtext="必填项,请填写信息"
                               value="{{ $data['order_city'] }}" class="layui-input" id="order_city">
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" name="order_area" lay-verify="required" lay-reqtext="必填项,请填写信息"
                               value="{{ $data['order_area'] }}" class="layui-input" id="order_area">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>详细地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="order_address" lay-verify="required" lay-reqtext="必填项,请填写信息"
                               value="{{ $data['order_address'] }}" class="layui-input" id="order_address">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label"><span class="x-red">*</span>发货单号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="tracking_number" value="{{ $data['tracking_number'] }}"
                                   class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">发货快递</label>
                        <div class="layui-input-inline" style="line-height:36px">
                            @if(($data['order_status'] == 1 || $data['order_status'] == 3) && $data['send_status'] < 2)
                                <select name="express_id" id="express_id" lay-filter="express_id">
                                    @foreach($express as $ex)
                                        <option value="{{ $ex['id'] }}" @if((string)$express_id === (string)$ex['id']) selected @endif>{{ $ex['express_name'] }}</option>
                                    @endforeach
                                </select>
                            @else
                                {{ $data['express_company'] ?? '' }}
                            @endif
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-block">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入内容" class="layui-textarea"
                                      name="remark">{{ $data['remark'] }}</textarea>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>数量</label>
                    <div class="layui-input-inline">
                        <input type="number" name="total_number" lay-verify="required" lay-reqtext="必填项,请填写信息" value="{{ $data['total_number'] }}" min="1" class="layui-input total-number" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>运费</label>
                    <div class="layui-input-inline">
                        <input type="number" name="freight" id="freight" value="{{ $data['freight'] }}" min="0" class="layui-input">
                    </div>
                    <div class="layui-input-inline" style="margin-left: 10px;">
                        <input type="checkbox" name="freight_type" lay-skin="switch" lay-text="指定运费|不指定运费" value="1" @if(($data['freight_type'] ?? 0) == 1) checked @endif>
                        <input type="hidden" name="freight_type" value="@if(($data['freight_type'] ?? 0) == 1) 1 @else 0 @endif" id="freight_type_hidden">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>订单金额</label>
                    <div class="layui-input-inline">
                        <input type="number" name="order_amount" id="order_amount" value="{{ $data['order_amount'] }}" min="0" class="layui-input" @if(!isset($data['amount_confirmed']) || $data['amount_confirmed'] != 1) readonly @endif>
                    </div>
                    <div class="layui-input-inline" style="margin-left: 10px;">
                        <input type="checkbox" name="confirm_amount" lay-skin="switch" lay-text="指定金额|自动计算" value="1" @if(isset($data['amount_confirmed']) && $data['amount_confirmed'] == 1) checked @endif>
                        <input type="hidden" name="amount_confirmed" value="@if(isset($data['amount_confirmed']) && $data['amount_confirmed'] == 1) 1 @else 0 @endif" id="amount_confirmed_hidden">
                    </div>
                </div>
                <input type="hidden" name="order_amount_type" value="@if(($data['amount_confirmed'] ?? 0) == 1) 1 @else 0 @endif" id="order_amount_type_hidden">
                <hr>
                <div class="layui-form-item">
                    <label class="layui-form-label"><b>订单状态：</b></label>
                    <div class="layui-input-block" style="line-height:36px">
                        订单状态：<b style="color:{{$data['order_status_color']}}">{{$data['order_status_name']}}</b><br>
                        发货状态：<b style="color:{{$data['send_status_color']}}">{{$data['send_status_name']}}</b><br>
                        操作人：{{$data['update_user']}}
                    </div>
                </div>
                <hr>
                <div class="layui-form-item">
                    <label for="L_repass" class="layui-form-label"></label>
                    <input type="hidden" value="{{ $data['id'] }}" name="id">
                    @if($data['order_status'] == 1)
                        <button class="layui-btn" lay-filter="add" lay-submit="">通过-转出库单</button>
                        <button class="layui-btn layui-btn-danger" lay-filter="cancel" lay-submit="">审核不通过</button>
                    @endif

                </div>
            </form>
        </div>
    </div>
    <script type="text/javascript" src="/static/admin/js/xcity.js"></script>
    <script>
        var reDataArr = JSON.parse(HTMLDecode("{{$goodsListStr}}"));
        var goodsIds = [];
        var ex_first_unit = 0;
        var ex_two_unit = 0;
        var ex_money = 0;

        function updateTotalNumber() {
            let total = 0;
            $('.goodsList2 .goods-number').each(function() {
                let num = parseInt($(this).val()) || 0;
                // 只统计非组合子商品的数量
                let $tr = $(this).closest('tr');
                if (!($tr.data('type') == 2 && $tr.data('pid') != 0)) {
                    total += num;
                }
            });
            $('.total-number').val(total);
            console.log('Total number updated to:', total);
        }

        function removeDiv(obj, i, type) {
            console.log('removeDiv called. Item index:', i, 'Action type:', type, 'DOM element:', obj);
            $(obj).parent().remove(); // Remove the row from the table
            
            if (type == 1) {
                // Adding item from "待选商品" to "已选商品"
                var batchOptions = '';
                if (reDataArr[i].batch_list && reDataArr[i].batch_list.length > 0) {
                    batchOptions += '<option value="">请选择批次</option>';
                    for (var b = 0; b < reDataArr[i].batch_list.length; b++) {
                        batchOptions += '<option value="' + reDataArr[i].batch_list[b] + '">' + reDataArr[i].batch_list[b] + '</option>';
                    }
                } else {
                    batchOptions = '<option value="">无可选批次</option>';
                }

                var htmlStr = `<tr data-item-id="${reDataArr[i].id}">` +
                        `<td onClick="removeDiv(this,${i},2)"><i class="iconfont" style="color:#DE1C31">&#xe6fe;</i></td>` +
                        `<td>${reDataArr[i].cate_name}</td>` +
                        `<td>${reDataArr[i].goods_name}</td>` +
                        `<td>${reDataArr[i].goods_price}</td>` +
                        `<td>
                            <input type="number" name="goods[${reDataArr[i].id}][goods_number]" value="1" min="1" step="1" class="layui-input goods-number">
                            <input type="hidden" name="goods[${reDataArr[i].id}][goods_id]" value="${reDataArr[i].id}">
                            <input type="hidden" name="goods[${reDataArr[i].id}][goods_price]" value="${reDataArr[i].goods_price}">
                            <input type="hidden" name="goods[${reDataArr[i].id}][is_give]" value="0">
                            <input type="hidden" name="goods[${reDataArr[i].id}][goods_pid]" value="${reDataArr[i].goods_pid || ''}">
                            <input type="hidden" name="goods[${reDataArr[i].id}][type]" value="${reDataArr[i].type || ''}">
                        </td>` +
                        `<td>否</td>` +
                        `<td>
                            <select name="goods[${reDataArr[i].id}][batch]" class="layui-input batch-select" lay-verify="required" lay-reqtext="请选择入库批次">
                                ${batchOptions}
                            </select>
                        </td>` +
                    `</tr>`;

        $(".goodsList2").prepend(htmlStr);
        layui.form.render('select');

        var $newSelect = $('.goodsList2 tr[data-item-id="' + reDataArr[i].id + '"]').find('.batch-select');
        if ($newSelect.find('option').length > 1) {
            $newSelect.val($newSelect.find('option:eq(1)').val());
        } else if ($newSelect.find('option').length === 1 && $newSelect.find('option').val() === '') {
            $newSelect.removeAttr('lay-verify');
            $newSelect.removeAttr('lay-reqtext');
        }
        layui.form.render('select');
    } else if (type == 2) {
        // Re-add to "待选商品" list
        var htmlStr = `<tr>
                        <td onClick="removeDiv(this,${i},1)"><i class="iconfont" style="color:#1ABC9C">&#xe6b9;</i></td>
                        <td>${reDataArr[i].cate_name}</td>
                        <td>${reDataArr[i].goods_sn}</td>
                        <td>${reDataArr[i].goods_name}</td>
                        <td>${reDataArr[i].goods_price}</td>
                        <td>${reDataArr[i].goods_sale_num}</td>
                        </tr>`;
        $(".goodsList1").append(htmlStr);
    }
    
    // 无论添加还是删除商品，都更新总数量和运费
    updateTotalNumber();
    updateFreightAndAmount();
}

        layui.use(['form', 'layer', 'jquery', 'code', 'laydate', 'element'], function () {
            $ = layui.jquery;
            var form = layui.form,
                layer = layui.layer;

            // 初始化批次选择
            $(document).ready(function() {
                // 初始化选择第一个批次（仅针对已存在的商品行，新添加的在removeDiv中处理）
                $('.goodsList2 .batch-select').each(function() {
                    if ($(this).find('option').length > 1 && !$(this).find('option:selected').val()) { // Check if not already set
                        $(this).val($(this).find('option:eq(1)').val());
                    } else if ($(this).find('option').length === 1 && $(this).find('option').val() === '') {
                        $(this).removeAttr('lay-verify');
                        $(this).removeAttr('lay-reqtext');
                    }
                });
                form.render('select'); // 重新渲染表单，使select生效
                updateTotalNumber(); // Initial total update on page load
                updateFreightAndAmount(); // Initial freight calculation on page load
                
                // 初始化组合商品数量关系
                initGroupGoodsQuantity();
            });

            // 表单提交前验证 (Layui form.verify is for form submit)
            form.verify({
                batch: function(value, item) {
                    // 只有当商品行可见且有批次选择框时才验证
                    // This verification is triggered by form submission, not on change.
                    var $batchSelects = $(item).closest('tr').find('.batch-select');
                    if ($batchSelects.length > 0 && !$batchSelects.val() && $batchSelects.attr('lay-verify') === 'required') {
                        return '请为所有商品选择入库批次';
                    }
                    return;
                }
            });

            // 初始化组合商品数量关系
            function initGroupGoodsQuantity() {
                $('.goodsList2 tr[data-type="2"][data-pid="0"]').each(function() {
                    let $mainTr = $(this);
                    let mainNum = parseInt($mainTr.find('.goods-number').val()) || 0;
                    let mainGoodsId = $mainTr.data('item-id');
                    
                    // 更新对应的子商品显示数量
                    $(`.goodsList2 tr[data-pid="${mainGoodsId}"]`).each(function() {
                        let groupNumber = parseInt($(this).data('group-number')) || 0;
                        let childNum = mainNum * groupNumber;
                        $(this).find('.goods-number').val(childNum);
                        $(this).find('input[name$="[goods_number]"]').val(childNum);
                    });
                });
            }

            // 计算并更新商品总数量
            function updateTotalNumber() {
                let total = 0;
                $('.goodsList2 .goods-number').each(function() { // 确保只计算已选商品的数量
                    let num = parseInt($(this).val()) || 0;
                    // 只统计非组合子商品的数量
                    let $tr = $(this).closest('tr');
                    if (!($tr.data('type') == 2 && $tr.data('pid') != 0)) {
                        total += num;
                    }
                });
                $('.total-number').val(total);
                console.log('Total number updated to:', total);
            }

            // 监听单个商品数量输入框的变化
            $(document).on('input change', '.goods-number', function() {
                console.log('Goods number input or change triggered. Value:', $(this).val());
                let currentValue = $(this).val();
                if (currentValue < 1 || isNaN(currentValue)) {
                    $(this).val(1);
                }
                
                // 如果是组合商品主商品，需要同步更新子商品数量
                let $tr = $(this).closest('tr');
                if ($tr.data('type') == 2 && $tr.data('pid') == 0) {
                    let mainNum = parseInt($(this).val()) || 0;
                    let mainGoodsId = $tr.data('item-id');
                    
                    // 更新对应的子商品显示数量
                    $(`.goodsList2 tr[data-pid="${mainGoodsId}"]`).each(function() {
                        let groupNumber = parseInt($(this).data('group-number')) || 0;
                        let childNum = mainNum * groupNumber;
                        $(this).find('.goods-number').val(childNum);
                        $(this).find('input[name$="[goods_number]"]').val(childNum);
                    });
                }
                
                updateTotalNumber();
                updateFreightAndAmount();
            });

            // 监听运费类型开关变化
            form.on('switch', function(data){
                var isChecked = data.elem.checked;
                if (data.elem.name === 'freight_type') {
                    $('#freight_type_hidden').val(isChecked ? 1 : 0);
                } else if (data.elem.name === 'confirm_amount') {
                    $('#amount_confirmed_hidden').val(isChecked ? 1 : 0);
                    $('#order_amount_type_hidden').val(isChecked ? 1 : 0);
                    if (isChecked) {
                        // 启用金额确认时，允许用户编辑金额
                        $('#order_amount').removeAttr('readonly');
                        // 启用金额确认时，禁用自动计算
                        disableAutoCalculation();
                    } else {
                        // 关闭金额确认时，禁止用户编辑金额
                        $('#order_amount').attr('readonly', 'readonly');
                        // 关闭金额确认时，启用自动计算
                        enableAutoCalculation();
                    }
                }
            });
            
            // 页面加载完成后，根据开关状态初始化自动计算功能
            $(document).ready(function() {
                // 如果金额确认开关未选中，则启用自动计算并禁止编辑金额
                if (!$('input[name="confirm_amount"]').prop('checked')) {
                    $('#order_amount').attr('readonly', 'readonly');
                    enableAutoCalculation();
                }
            });
            
            function disableAutoCalculation() {
                // 禁用自动计算相关事件
                $('#freight').off('input change');
                $('.goods-number').off('input change');
            }
            
            function enableAutoCalculation() {
                // 重新绑定自动计算相关事件
                $('#freight').on('input change', function() {
                    console.log('Freight changed. New value:', $(this).val());
                    let currentFreight = parseFloat($(this).val()) || 0;
            
                    // 计算商品总价（不含运费）
                    let goodsTotal = 0;
                    $('.goodsList2 tr').each(function() {
                        let price = parseFloat($(this).find('input[name$="[goods_price]"]').val()) || 0;
                        let num = parseInt($(this).find('input[name$="[goods_number]"]').val()) || 0;
                        let isGive = parseInt($(this).find('input[name$="[is_give]"]').val()) || 0;
                        let goods_pid = parseInt($(this).find('input[name$="[goods_pid]"]').val()) || 0;
                        let type = parseInt($(this).find('input[name$="[type]"]').val()) || 0;
                        if(isGive === 0) { // 只计算非赠品金额
                            goodsTotal += price * num;
                        }
                    });
            
                    // 更新订单总金额（商品总价 + 运费）
                    let totalAmount = goodsTotal + currentFreight;
                    $('#order_amount').val(totalAmount.toFixed(2));
                });
                
                // 重新绑定商品数量变化事件
                $(document).off('input change', '.goods-number').on('input change', '.goods-number', function() {
                    console.log('Goods number input or change triggered. Value:', $(this).val());
                    let currentValue = $(this).val();
                    if (currentValue < 1 || isNaN(currentValue)) {
                        $(this).val(1);
                    }
                    
                    // 如果是组合商品主商品，需要同步更新子商品数量
                    let $tr = $(this).closest('tr');
                    if ($tr.data('type') == 2 && $tr.data('pid') == 0) {
                        let mainNum = parseInt($(this).val()) || 0;
                        let mainGoodsId = $tr.data('item-id');
                        
                        // 更新对应的子商品显示数量
                        $(`.goodsList2 tr[data-pid="${mainGoodsId}"]`).each(function() {
                            let groupNumber = parseInt($(this).data('group-number')) || 0;
                            let childNum = mainNum * groupNumber;
                            $(this).find('.goods-number').val(childNum);
                            $(this).find('input[name$="[goods_number]"]').val(childNum);
                        });
                    }
                    
                    updateTotalNumber();
                    updateFreightAndAmount();
                });
            }
            
            // 监听运费输入框变化
            $(document).on('input change', '#freight', function() {
                console.log('Freight changed. New value:', $(this).val());
                let currentFreight = parseFloat($(this).val()) || 0;
        
                // 计算商品总价（不含运费）
                let goodsTotal = 0;
                $('.goodsList2 tr').each(function() {
                    let price = parseFloat($(this).find('input[name$="[goods_price]"]').val()) || 0;
                    let num = parseInt($(this).find('input[name$="[goods_number]"]').val()) || 0;
                    let isGive = parseInt($(this).find('input[name$="[is_give]"]').val()) || 0;
                    let goods_pid = parseInt($(this).find('input[name$="[goods_pid]"]').val()) || 0;
                    let type = parseInt($(this).find('input[name$="[type]"]').val()) || 0;
                    if(isGive === 0) { // 只计算非赠品金额
                        goodsTotal += price * num;
                    }
                });
        
                // 更新订单总金额（商品总价 + 运费）
                let totalAmount = goodsTotal + currentFreight;
                $('#order_amount').val(totalAmount.toFixed(2));
            });

            // 监听提交
            form.on('submit(add)', function (data) {
                console.log('Form submit (add) triggered.');
                // 验证批次选择
                let valid = true;
                $('.goodsList2 .batch-select').each(function() { // 确保只验证已选商品的批次
                    if ($(this).attr('lay-verify') === 'required' && !$(this).val()) {
                        layer.alert('请为所有商品选择入库批次');
                        valid = false;
                        return false; // Break .each loop
                    }
                });
                if (!valid) {
                    return false; // Prevent form submission
                }

                if (confirm("你确定通过-转出库单吗？")) {
                    console.log('Submitting form data via AJAX (add).', data.field);
                    //发异步，把数据提交给php
                    $.ajax({
                        type: 'POST',
                        url: '/admin/order/orderEdit',
                        data: data.field,
                        dataType: 'json',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        success: function (data) {
                            console.log('AJAX success for add:', data);
                            layer.alert(data.msg)
                            if (data.code == 1) {
                                //关闭当前frame
                                xadmin.close();
                                // 可以对父窗口进行刷新
                                xadmin.father_reload();
                            }
                        },
                        error: function (xhr, type) {
                            console.error('AJAX error for add:', xhr, type);
                            alert('Ajax error!')
                        }
                    });
                }
                return false; // Prevent default form submission
            });
            //监听提交
            form.on('submit(cancel)', function (data) {
                console.log('Form submit (cancel) triggered.');
                //发异步，把数据提交给php
                if (confirm("你确定审核不通过吗？")) {
                    console.log('Submitting form data via AJAX (cancel).', data.field);
                    $.ajax({
                        type: 'POST',
                        url: '/admin/order/orderEdit?cancel=1',
                        data: data.field,
                        dataType: 'json',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        success: function (data) {
                            console.log('AJAX success for cancel:', data);
                            layer.alert(data.msg)
                            if (data.code == 1) {
                                //关闭当前frame
                                xadmin.close();
                                // 可以对父窗口进行刷新
                                xadmin.father_reload();
                            }
                        },
                        error: function (xhr, type) {
                            console.error('AJAX error for cancel:', xhr, type);
                            alert('Ajax error!')
                        }
                    });
                }
                return false; // Prevent default form submission
            });

            // 监听快递下拉切换
            form.on('select(express_id)', function(data){
                console.log('Express select changed. New value:', data.value);
                updateFreightAndAmount();
            });

            // 监听省市区地址输入框变化 - 修改为blur事件
            $(document).on('blur', '#order_province, #order_city, #order_area, #order_address', function() {
                // 只有当所有地址字段都有值时才触发计算
                var province = $('#order_province').val();
                var city = $('#order_city').val();
                var area = $('#order_area').val();
                var address = $('#order_address').val();
                
                if(province && city && area && address) {
                    console.log('Address field blur:', this.id);
                    updateFreightAndAmount();
                }
            });

        });

        // 修改updateFreightAndAmount函数，确保地址字段完整才请求
        function updateFreightAndAmount() {
            console.log('updateFreightAndAmount called.');
            // 检查是否启用了金额确认，如果启用了则不自动更新金额
            if ($('input[name="confirm_amount"]').prop('checked')) {
                console.log('Amount confirmed, skipping auto-update');
                return;
            }
            
            var express_id = $('#express_id').val();
            var goods_data = [];
            var store_id = "{{ $data['store_id'] ?? 0 }}";
            
            // 获取省市区地址信息
            var order_province = $('input[name="order_province"]').val();
            var order_city = $('input[name="order_city"]').val();
            var order_area = $('input[name="order_area"]').val();
            var order_address = $('input[name="order_address"]').val();
            
            // 只有当所有地址字段都有值时才继续计算
            if(!order_province || !order_city || !order_area || !order_address) {
                console.log('Address information incomplete, skipping freight calculation');
                return;
            }

            // 收集商品数据，包括is_give状态
            $('.goodsList2 tr').each(function() {
                var goods_id = $(this).find('input[name$="[goods_id]"]').val();
                var goods_num = $(this).find('input[name$="[goods_number]"]').val();
                var goods_price = $(this).find('input[name$="[goods_price]"]').val();
                var is_give = $(this).find('input[name$="[is_give]"]').val();
                var goods_pid = $(this).find('input[name$="[goods_pid]"]').val();
                var type = $(this).find('input[name$="[type]"]').val();
                // 添加 goods_weight_m 字段
                var goods_weight_m = $(this).find('input[name$="[goods_weight_m]"]').val();
                if(goods_id && goods_num) {
                    var goods_item = {
                        goods_id: goods_id,
                        goods_num: goods_num,
                        goods_price: goods_price, // 赠品价格设为0
                        is_give: is_give || 0,// 默认0表示不是赠品
                        goods_pid: goods_pid,
                        type: type,
                        goods_weight_m: goods_weight_m || 0 // 添加重量字段
                    };
                    goods_data.push(goods_item);
                }
            });

            $.ajax({
                type: 'POST',
                url: '/admin/order/freightAndAmount',
                data: {
                    express_id: express_id,
                    goods_info_arr: goods_data,
                    store_id: store_id,
                    province: order_province,
                    city: order_city,
                    area: order_area,
                    address: order_address,
                    total_number: $('.total-number').val()
                },
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                },
                success: function (res) {
                    console.log('Freight and Amount AJAX success:', res);
                    if(res.code === 1) {
                        $('#freight').val(res.data.express_fee);
                        $('#order_amount').val(res.data.total_money);
                        // 根据需求，更新总数量为接口返回的num值
                        $('.total-number').val(res.data.num);
                    } else {
                        layer.msg(res.msg || '计算失败', {icon: 2});
                    }
                },
                error: function (xhr, type, errorThrown) {
                    console.error('Freight and Amount AJAX error:', xhr, type, errorThrown);
                    layer.msg('请求失败', {icon: 2});
                }
            });
        }

        //HTML反转义 (Utility function)
        function HTMLDecode(text) {
            var temp = document.createElement("div");
            temp.innerHTML = text;
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }

        function checkWeight(input) {
            // 只允许输入数字和一个小数点
            input.value = input.value.replace(/[^\d.]/g, '');
            // 确保只有一个小数点
            if(input.value.split('.').length > 2) {
                input.value = input.value.slice(0, input.value.lastIndexOf('.'));
            }
            // 确保小数点后最多三位
            if(input.value.indexOf('.') > -1) {
                var decimalPart = input.value.split('.')[1];
                if(decimalPart && decimalPart.length > 3) {
                    input.value = input.value.slice(0, input.value.indexOf('.') + 4);
                }
            }
        }
    </script>
@endsection

